package com.yuntsg.ruiijn.controller.search;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuntsg.nnsfcp.common.utils.UserUtil;
import com.yuntsg.ruiijn.databse_search.entity.FileFeedback;
import com.yuntsg.ruiijn.databse_search.entity.FileRecord;
import com.yuntsg.ruiijn.databse_search.service.FileFeedbackService;
import com.yuntsg.ruiijn.databse_search.service.FileRecordsService;
import common.bean.R;
import common.util.AesEncryptUtils;
import common.util.FullTextUtil;
import common.util.MinioUtil;
import common.vo.Scenario;
//import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@SuppressWarnings("all")
@RequestMapping("manager/file/feedback")
@Slf4j
public class FileFeedbackController {

    private final FileFeedbackService fileFeedbackService;

    private final MinioUtil minioUtil;

    private final FileRecordsService fileRecordsService;

    @Resource
    UserUtil userUtil;


    @PostMapping("/add")
//    @ApiOperation(value = "新增文件反馈")
    public R add(@RequestBody FileFeedback fileFeedback) {

        FileRecord fileRecord = fileRecordsService.getById(fileFeedback.getRid());
        if (null != fileRecord) {
            fileFeedback.setOrginInfo("/oss/" + fileRecord.getFilePath());
        }

        if (null != fileFeedback.getLinePath() && StrUtil.isNotEmpty(fileFeedback.getLinePath())) {
            ByteArrayInputStream stream = null;
            try {
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] bt = decoder.decodeBuffer(StrUtil.subAfter(fileFeedback.getLinePath(), "base64,", true));
                stream = new ByteArrayInputStream(bt);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String lin_path = minioUtil.upload(stream, userUtil.getUid(), DateUtil.today(), RandomUtil.randomString(6) + ".png", Scenario.view);
            fileFeedback.setLinePath("/oss/" + lin_path);
        }
        if (StrUtil.isNotEmpty(fileFeedback.getTargetPm())) {
            Map<String, String> map = new HashMap<>();
            if (NumberUtil.isNumber(fileFeedback.getTargetPm())) {
                map = FullTextUtil.fetchPdfUrl(fileFeedback.getTargetPm(), 0);
            } else {
                map = FullTextUtil.fetchPdfUrl(AesEncryptUtils.decrypt(fileFeedback.getTargetPm()), 0);
            }

            if (null != map && map.containsKey("pdfUrl") && StrUtil.isNotEmpty(map.get("pdfUrl"))) {
                fileFeedback.setTargetInfo(map.get("pdfUrl").replaceAll("https://attach.pubtsg.com/", "/"));
            }
        }
        fileFeedbackService.saveOrUpdate(fileFeedback.setDoneStatus(0).setUid(userUtil.getUid()).setUploadTime(System.currentTimeMillis()));
        return R.ok();
    }

    //    @ApiOperation(value = "反馈列表")
    @RequestMapping("/list")
    public R searchImageId(Integer hasError,
                           Integer rid,
                           Integer uid,
                           Integer doneStatus,
                           @RequestParam("page") Integer page,
                           @RequestParam("size") Integer size) {

        Page<FileFeedback> data = fileFeedbackService.page(new Page<>(page, size), Wrappers.<FileFeedback>lambdaQuery().eq(ObjectUtil.isNotEmpty(rid), FileFeedback::getRid, rid)
                .eq(ObjectUtil.isNotEmpty(uid), FileFeedback::getUid, uid)
                .eq(ObjectUtil.isNotEmpty(doneStatus), FileFeedback::getDoneStatus, doneStatus)
                .eq(ObjectUtil.isNotEmpty(hasError), FileFeedback::getHasError, hasError)
                .orderByDesc(FileFeedback::getId));


        return R.ok().put("count", data.getTotal()).put("data", data.getRecords());
    }


    /**
     * 更新状态
     *
     * @param id
     * @return
     */
    @RequestMapping("/update")
    public R searchImageId(@RequestParam("id") Integer id) {
        fileFeedbackService.update(Wrappers.<FileFeedback>lambdaUpdate().eq(FileFeedback::getId, id).set(FileFeedback::getDoneStatus, 1));
        return R.ok();
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */

    @GetMapping("/delete")
    public R deleteBatch(@RequestParam(value = "ids[]") String[] ids) {
        boolean result = fileFeedbackService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }


}
